home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / xulrunner-1.9.0.14 / python / xpcom / xpt.py < prev   
Encoding:
Python Source  |  2006-11-08  |  17.6 KB  |  481 lines

  1. # ***** BEGIN LICENSE BLOCK *****
  2. # Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. #
  4. # The contents of this file are subject to the Mozilla Public License Version
  5. # 1.1 (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. # http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS IS" basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # The Original Code is the Python XPCOM language bindings.
  15. #
  16. # The Initial Developer of the Original Code is
  17. # ActiveState Tool Corp.
  18. # Portions created by the Initial Developer are Copyright (C) 2000, 2001
  19. # the Initial Developer. All Rights Reserved.
  20. #
  21. # Contributor(s):
  22. #   David Ascher <DavidA@ActiveState.com> (original author)
  23. #   Mark Hammond <mhammond@skippinet.com.au>
  24. #
  25. # Alternatively, the contents of this file may be used under the terms of
  26. # either the GNU General Public License Version 2 or later (the "GPL"), or
  27. # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28. # in which case the provisions of the GPL or the LGPL are applicable instead
  29. # of those above. If you wish to allow use of your version of this file only
  30. # under the terms of either the GPL or the LGPL, and not to allow others to
  31. # use your version of this file under the terms of the MPL, indicate your
  32. # decision by deleting the provisions above and replace them with the notice
  33. # and other provisions required by the GPL or the LGPL. If you do not delete
  34. # the provisions above, a recipient may use your version of this file under
  35. # the terms of any one of the MPL, the GPL or the LGPL.
  36. #
  37. # ***** END LICENSE BLOCK *****
  38.  
  39. """
  40. Program: xpt.py
  41.  
  42. Task: describe interfaces etc using XPCOM reflection.
  43.  
  44. Subtasks:
  45.      output (nearly) exactly the same stuff as xpt_dump, for verification
  46.      output Python source code that can be used as a template for an interface
  47.  
  48. Status: Works pretty well if you ask me :-)
  49.  
  50. Author:
  51.    David Ascher did an original version that parsed XPT files
  52.    directly.  Mark Hammond changed it to use the reflection interfaces,
  53.    but kept most of the printing logic.
  54.  
  55.  
  56. Revision:
  57.  
  58.   0.1: March 6, 2000
  59.   0.2: April 2000 - Mark removed lots of Davids lovely parsing code in favour
  60.                     of the new xpcom interfaces that provide this info.
  61.  
  62.   May 2000 - Moved into Perforce - track the log there!
  63.   Early 2001 - Moved into the Mozilla CVS tree - track the log there!  
  64.  
  65. Todo:
  66.   Fill out this todo list.
  67.  
  68. """
  69.  
  70. import string, sys
  71. import xpcom
  72. import xpcom._xpcom
  73.  
  74. from xpcom_consts import *
  75.  
  76. class Interface:
  77.     def __init__(self, iid):
  78.         iim = xpcom._xpcom.XPTI_GetInterfaceInfoManager()
  79.         if hasattr(iid, "upper"): # Is it a stringy thing.
  80.             item = iim.GetInfoForName(iid)
  81.         else:
  82.             item = iim.GetInfoForIID(iid)
  83.         self.interface_info = item
  84.         self.namespace = "" # where does this come from?
  85.         self.methods = Methods(item)
  86.         self.constants = Constants(item)
  87.  
  88.     # delegate attributes to the real interface
  89.     def __getattr__(self, attr):
  90.         return getattr(self.interface_info, attr)
  91.  
  92.     def GetParent(self):
  93.         try:
  94.             raw_parent = self.interface_info.GetParent()
  95.             if raw_parent is None:
  96.                 return None
  97.             return Interface(raw_parent.GetIID())
  98.         except xpcom.Exception:
  99.             # Parent interface is probably not scriptable - assume nsISupports.
  100.             if xpcom.verbose:
  101.                 # The user may be confused as to why this is happening!
  102.                 print "The parent interface of IID '%s' can not be located - assuming nsISupports"
  103.             return Interface(xpcom._xpcom.IID_nsISupports)
  104.  
  105.     def Describe_Python(self):
  106.         method_reprs = []
  107.         methods = filter(lambda m: not m.IsNotXPCOM(), self.methods)
  108.         for m in methods:
  109.             method_reprs.append(m.Describe_Python())
  110.         method_joiner = "\n"
  111.         methods_repr = method_joiner.join(method_reprs)
  112.         return \
  113. """from xpcom import ServerException, nsError
  114. class %s:
  115.     _com_interfaces_ = xpcom.components.interfaces.%s
  116.     # If this object needs to be registered, the following 2 are also needed.
  117.     # _reg_clsid_ = "{a new clsid generated for this object}"
  118.     # _reg_contractid_ = "@providername.org/object-name;1"\n%s""" % (self.GetName(), self.GetIID().name, methods_repr)
  119.  
  120.     def Describe(self):
  121.         # Make the IID look like xtp_dump - "(" instead of "{"
  122.         iid_use = "(" + str(self.GetIID())[1:-1] + ")"
  123.         s = '   - '+self.namespace+'::'+ self.GetName() + ' ' + iid_use + ':\n'
  124.  
  125.         parent = self.GetParent()
  126.         if parent is not None:
  127.             s = s + '      Parent: ' + parent.namespace + '::' + parent.GetName() + '\n'
  128.         s = s + '      Flags:\n'
  129.         if self.IsScriptable(): word = 'TRUE'
  130.         else: word = 'FALSE'
  131.         s = s + '         Scriptable: ' + word + '\n'
  132.         s = s + '      Methods:\n'
  133.         methods = filter(lambda m: not m.IsNotXPCOM(), self.methods)
  134.         if len(methods):
  135.             for m in methods:
  136.                 s = s + '   ' + m.Describe() + '\n'
  137.         else:
  138.             s = s + '         No Methods\n'
  139.         s = s + '      Constants:\n'
  140.         if self.constants:
  141.             for c in self.constants:
  142.                 s = s + '         ' + c.Describe() + '\n'
  143.         else:
  144.             s = s + '         No Constants\n'
  145.  
  146.         return s
  147.  
  148. # A class that allows caching and iterating of methods.
  149. class Methods:
  150.     def __init__(self, interface_info):
  151.         self.interface_info = interface_info
  152.         try:
  153.             self.items = [None] * interface_info.GetMethodCount()
  154.         except xpcom.Exception:
  155.             if xpcom.verbose:
  156.                 print "** GetMethodCount failed?? - assuming no methods"
  157.             self.items = []
  158.     def __len__(self):
  159.         return len(self.items)
  160.     def __getitem__(self, index):
  161.         ret = self.items[index]
  162.         if ret is None:
  163.             mi = self.interface_info.GetMethodInfo(index)
  164.             ret = self.items[index] = Method(mi, index, self.interface_info)
  165.         return ret
  166.  
  167. class Method:
  168.  
  169.     def __init__(self, method_info, method_index, interface_info = None):
  170.         self.interface_info = interface_info
  171.         self.method_index = method_index
  172.         self.flags, self.name, param_descs, self.result_desc = method_info
  173.         # Build the params.
  174.         self.params = []
  175.         pi=0
  176.         for pd in param_descs:
  177.             self.params.append( Parameter(pd, pi, method_index, interface_info) )
  178.             pi = pi + 1
  179.         # Run over the params setting the "sizeof" params to hidden.
  180.         for p in self.params:
  181.             td = p.type_desc
  182.             tag = XPT_TDP_TAG(td[0])
  183.             if tag==T_ARRAY and p.IsIn():
  184.                 self.params[td[1]].hidden_indicator = 2
  185.             elif tag in [T_PSTRING_SIZE_IS, T_PWSTRING_SIZE_IS] and p.IsIn():
  186.                 self.params[td[1]].hidden_indicator = 1
  187.  
  188.     def IsGetter(self):
  189.         return (self.flags & XPT_MD_GETTER)
  190.     def IsSetter(self):
  191.         return (self.flags & XPT_MD_SETTER)
  192.     def IsNotXPCOM(self):
  193.         return (self.flags & XPT_MD_NOTXPCOM)
  194.     def IsConstructor(self):
  195.         return (self.flags & XPT_MD_CTOR)
  196.     def IsHidden(self):
  197.         return (self.flags & XPT_MD_HIDDEN)
  198.  
  199.     def Describe_Python(self):
  200.         if self.method_index < 3: # Ignore QI etc
  201.             return ""
  202.         base_name = self.name
  203.         if self.IsGetter():
  204.             name = "get_%s" % (base_name,)
  205.         elif self.IsSetter():
  206.             name = "set_%s" % (base_name,)
  207.         else:
  208.             name = base_name
  209.         param_decls = ["self"]
  210.         in_comments = []
  211.         out_descs = []
  212.         result_comment = "Result: void - None"
  213.         for p in self.params:
  214.             in_desc, in_desc_comments, out_desc, this_result_comment = p.Describe_Python()
  215.             if in_desc is not None:
  216.                 param_decls.append(in_desc)
  217.             if in_desc_comments is not None:
  218.                 in_comments.append(in_desc_comments)
  219.             if out_desc is not None:
  220.                 out_descs.append(out_desc)
  221.             if this_result_comment is not None:
  222.                 result_comment = this_result_comment
  223.         joiner = "\n        # "
  224.         in_comment = out_desc = ""
  225.         if in_comments: in_comment = joiner + joiner.join(in_comments)
  226.         if out_descs: out_desc = joiner + joiner.join(out_descs)
  227.  
  228.         return """    def %s( %s ):
  229.         # %s%s%s
  230.         raise ServerException(nsError.NS_ERROR_NOT_IMPLEMENTED)""" % (name, ", ".join(param_decls), result_comment, in_comment, out_desc)
  231.  
  232.     def Describe(self):
  233.         s = ''
  234.         if self.IsGetter():
  235.             G = 'G'
  236.         else:
  237.             G = ' '
  238.         if self.IsSetter():
  239.             S = 'S'
  240.         else: S = ' '
  241.         if self.IsHidden():
  242.             H = 'H'
  243.         else:
  244.             H = ' '
  245.         if self.IsNotXPCOM():
  246.             N = 'N'
  247.         else:
  248.             N = ' '
  249.         if self.IsConstructor():
  250.             C = 'C'
  251.         else:
  252.             C = ' '
  253.  
  254.         def desc(a): return a.Describe()
  255.         method_desc = string.join(map(desc, self.params), ', ')
  256.         result_type = TypeDescriber(self.result_desc[0], None)
  257.         return_desc = result_type.Describe()
  258.         i = string.find(return_desc, 'retval ')
  259.         if i != -1:
  260.             return_desc = return_desc[:i] + return_desc[i+len('retval '):]
  261.         return G+S+H+N+C+' '+return_desc+' '+self.name + '('+ method_desc + ');'
  262.  
  263. class Parameter:
  264.     def __init__(self,  param_desc, param_index, method_index, interface_info = None):
  265.         self.param_flags, self.type_desc = param_desc
  266.         self.hidden_indicator = 0 # Is this a special "size" type param that will be hidden from Python?
  267.         self.param_index = param_index
  268.         self.method_index= method_index
  269.         self.interface_info = interface_info
  270.     def __repr__(self):
  271.         return "<param %(param_index)d (method %(method_index)d) - flags = 0x%(param_flags)x, type = %(type_desc)s>" % self.__dict__
  272.     def IsIn(self):
  273.         return XPT_PD_IS_IN(self.param_flags)
  274.     def IsOut(self):
  275.         return XPT_PD_IS_OUT(self.param_flags)
  276.     def IsInOut(self):
  277.         return self.IsIn() and self.IsOut()
  278.     def IsRetval(self):
  279.         return XPT_PD_IS_RETVAL(self.param_flags)
  280.     def IsShared(self):
  281.         return XPT_PD_IS_SHARED(self.param_flags)
  282.     def IsDipper(self):
  283.         return XPT_PD_IS_DIPPER(self.param_flags)
  284.  
  285.     def Describe_Python(self):
  286.         name = "param%d" % (self.param_index,)
  287.         if self.hidden_indicator:
  288.             # Could remove the comment - Im trying to tell the user where that param has
  289.             # gone from the signature!
  290.             return None, "%s is a hidden parameter" % (name,), None, None
  291.         t = TypeDescriber(self.type_desc[0], self)
  292.         decl = in_comment = out_comment = result_comment = None
  293.         type_desc = t.Describe()
  294.         if self.IsIn() and not self.IsDipper():
  295.             decl = name
  296.             extra=""
  297.             if self.IsOut():
  298.                 extra = "Out"
  299.             in_comment = "In%s: %s: %s" % (extra, name, type_desc)
  300.         elif self.IsOut() or self.IsDipper():
  301.             if self.IsRetval():
  302.                 result_comment = "Result: %s" % (type_desc,)
  303.             else:
  304.                 out_comment = "Out: %s" % (type_desc,)
  305.         return decl, in_comment, out_comment, result_comment
  306.  
  307.     def Describe(self):
  308.         parts = []
  309.         if self.IsInOut():
  310.             parts.append('inout')
  311.         elif self.IsIn():
  312.             parts.append('in')
  313.         elif self.IsOut():
  314.             parts.append('out')
  315.  
  316.         if self.IsDipper(): parts.append("dipper")
  317.         if self.IsRetval(): parts.append('retval')
  318.         if self.IsShared(): parts.append('shared')
  319.         t = TypeDescriber(self.type_desc[0], self)
  320.         type_str = t.Describe()
  321.         parts.append(type_str)
  322.         return string.join(parts)
  323.  
  324. # A class that allows caching and iterating of constants.
  325. class Constants:
  326.     def __init__(self, interface_info):
  327.         self.interface_info = interface_info
  328.         try:
  329.             self.items = [None] * interface_info.GetConstantCount()
  330.         except xpcom.Exception:
  331.             if xpcom.verbose:
  332.                 print "** GetConstantCount failed?? - assuming no constants"
  333.             self.items = []
  334.     def __len__(self):
  335.         return len(self.items)
  336.     def __getitem__(self, index):
  337.         ret = self.items[index]
  338.         if ret is None:
  339.             ci = self.interface_info.GetConstant(index)
  340.             ret = self.items[index] = Constant(ci)
  341.         return ret
  342.  
  343. class Constant:
  344.     def __init__(self, ci):
  345.         self.name, self.type, self.value = ci
  346.  
  347.     def Describe(self):
  348.         return TypeDescriber(self.type, None).Describe() + ' ' +self.name+' = '+str(self.value)+';'
  349.  
  350.     __str__ = Describe
  351.  
  352. def MakeReprForInvoke(param):
  353.     tag = param.type_desc[0] & XPT_TDP_TAGMASK
  354.     if tag == T_INTERFACE:
  355.         i_info = param.interface_info
  356.         try:
  357.             iid = i_info.GetIIDForParam(param.method_index, param.param_index)
  358.         except xpcom.Exception:
  359.             # IID not available (probably not scriptable) - just use nsISupports.
  360.             iid = xpcom._xpcom.IID_nsISupports
  361.         return param.type_desc[0], 0, 0, str(iid)
  362.     elif tag == T_ARRAY:
  363.         i_info = param.interface_info
  364.         array_desc = i_info.GetTypeForParam(param.method_index, param.param_index, 1)
  365.         if XPT_TDP_TAG(array_desc[0]) in (T_INTERFACE, T_INTERFACE_IS):
  366.             iid = str(i_info.GetIIDForParam(param.method_index, param.param_index))
  367.         else:
  368.             iid = None
  369.         return param.type_desc[:-1] + (iid, array_desc[0])
  370.  
  371.     return param.type_desc
  372.  
  373.  
  374. class TypeDescriber:
  375.     def __init__(self, type_flags, param):
  376.         self.type_flags = type_flags
  377.         self.tag = XPT_TDP_TAG(self.type_flags)
  378.         self.param = param
  379.     def IsPointer(self):
  380.         return XPT_TDP_IS_POINTER(self.type_flags)
  381.     def IsUniquePointer(self):
  382.         return XPT_TDP_IS_UNIQUE_POINTER(self.type_flags)
  383.     def IsReference(self):
  384.         return XPT_TDP_IS_REFERENCE(self.type_flags)
  385.     def repr_for_invoke(self):
  386.         return (self.type_flags,)
  387.     def GetName(self):
  388.         is_ptr = self.IsPointer()
  389.         data = type_info_map.get(self.tag)
  390.         if data is None:
  391.             data = ("unknown",)
  392.         if self.IsReference():
  393.             if len(data) > 2:
  394.                 return data[2]
  395.             return data[0] + " &"
  396.         if self.IsPointer():
  397.             if len(data)>1:
  398.                 return data[1]
  399.             return data[0] + " *"
  400.         return data[0]
  401.  
  402.     def Describe(self):
  403.         if self.tag == T_ARRAY:
  404.             # NOTE - Adding a type specifier to the array is different from xpt_dump.exe
  405.             if self.param is None or self.param.interface_info is None:
  406.                 type_desc = "" # Don't have explicit info about the array type :-(
  407.             else:
  408.                 i_info = self.param.interface_info
  409.                 type_code = i_info.GetTypeForParam(self.param.method_index, self.param.param_index, 1)
  410.                 type_desc = TypeDescriber( type_code[0], None).Describe()
  411.             return self.GetName() + "[" + type_desc + "]" 
  412.         elif self.tag == T_INTERFACE:
  413.             if self.param is None or self.param.interface_info is None:
  414.                 return "nsISomething" # Don't have explicit info about the IID :-(
  415.             i_info = self.param.interface_info
  416.             m_index = self.param.method_index
  417.             p_index = self.param.param_index
  418.             try:
  419.                 iid = i_info.GetIIDForParam(m_index, p_index)
  420.                 return iid.name
  421.             except xpcom.Exception:
  422.                 return "nsISomething"
  423.         return self.GetName()
  424.  
  425. # These are just for output purposes, so should be
  426. # the same as xpt_dump uses
  427. type_info_map = {
  428.     T_I8                : ("int8",),
  429.     T_I16               : ("int16",),
  430.     T_I32               : ("int32",),
  431.     T_I64               : ("int64",),
  432.     T_U8                : ("uint8",),
  433.     T_U16               : ("uint16",),
  434.     T_U32               : ("uint32",),
  435.     T_U64               : ("uint64",),
  436.     T_FLOAT             : ("float",),
  437.     T_DOUBLE            : ("double",),
  438.     T_BOOL              : ("boolean",),
  439.     T_CHAR              : ("char",),
  440.     T_WCHAR             : ("wchar_t", "wstring"),
  441.     T_VOID              : ("void",),
  442.     T_IID               : ("reserved", "nsIID *", "nsIID &"),
  443.     T_DOMSTRING         : ("DOMString",),
  444.     T_CHAR_STR          : ("reserved", "string"),
  445.     T_WCHAR_STR         : ("reserved", "wstring"),
  446.     T_INTERFACE         : ("reserved", "Interface"),
  447.     T_INTERFACE_IS      : ("reserved", "InterfaceIs *"),
  448.     T_ARRAY             : ("reserved", "Array"),
  449.     T_PSTRING_SIZE_IS   : ("string", "string_s"),
  450.     T_PWSTRING_SIZE_IS  : ("unicode", "wstring_s"),
  451.     T_UTF8STRING        : ("utf8string", "utf8string"),
  452.     T_CSTRING           : ("string", "cstring"),
  453.     T_ASTRING           : ("unicode", "astring"),
  454. }
  455.  
  456. def dump_interface(iid, mode):
  457.     interface = Interface(iid)
  458.     describer_name = "Describe"
  459.     if mode == "xptinfo": mode = None
  460.     if mode is not None:
  461.         describer_name = describer_name + "_" + mode.capitalize()
  462.     describer = getattr(interface, describer_name)
  463.     print describer()
  464.  
  465. if __name__=='__main__':
  466.     if len(sys.argv) == 1:
  467.         print "Usage: xpt.py [-xptinfo] interface_name, ..."
  468.         print "  -info: Dump in a style similar to the xptdump tool"
  469.         print "Dumping nsISupports and nsIInterfaceInfo"
  470.         sys.argv.append('nsIInterfaceInfo')
  471.         sys.argv.append('-xptinfo')
  472.         sys.argv.append('nsISupports')
  473.         sys.argv.append('nsIInterfaceInfo')
  474.  
  475.     mode = "Python"
  476.     for i in sys.argv[1:]:
  477.         if i[0] == "-":
  478.             mode = i[1:]
  479.         else:
  480.             dump_interface(i, mode)
  481.